package com.spring.utils.api_v4.controller;


import com.alibaba.fastjson.JSONObject;
import com.spring.utils.api_v4.annotation.ResponseResult;
import com.spring.utils.api_v4.pojo.Role;
import com.spring.utils.api_v4.pojo.UserInfo;
import com.spring.utils.api_v4.pojo.response.BizException;
import com.spring.utils.api_v4.pojo.response.ResultCode;
import com.spring.utils.api_v4.service.ISystemService;
import com.spring.utils.api_v4.service.IUserService;
import com.spring.utils.api_v4.service.IVerifyCodeGen;
import com.spring.utils.api_v4.util.VerifyCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Base64;
import java.util.List;
import java.util.Optional;

@RestController
@ResponseResult
@RequestMapping("/api")
public class LoginController {
    @Autowired private IVerifyCodeGen verifyCodeGen;
    @Autowired private IUserService userService;
    @Autowired private ISystemService systemService;

    /**
     * 获取验证码
     * @return
     */
    @GetMapping("/captcha")
    public JSONObject getCaptcha() throws IOException {
         //1、获取base64编码器
        Base64.Encoder encoder = Base64.getEncoder();
        // 2、生成验证码生成器
        VerifyCode verifyCode = verifyCodeGen.generate(80, 28);
        // 3、获取验证码
        String code = verifyCode.getCode();
        // 4、将图片进行base64编码
        String imgBase64 = encoder.encodeToString(verifyCode.getImgBytes());

        // 5、构建结果map
        JSONObject rs = new JSONObject();
        rs.put("key", code);
        rs.put("svg", String.format("<img src=\"data:image/jpg;base64,%s\" />", imgBase64));
        return rs;
    }

    @PostMapping("/login")
    public JSONObject login(@RequestBody JSONObject login) {
        String username = login.getString("username");
        String password = login.getString("password");
        // 1、如果账号或密码为空
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            throw new BizException(ResultCode.PARAM_IS_BLANK);
        }
        Optional<UserInfo> op = userService.checkLogin(username, password);
        // 2、如果账户密码错误
        if(op.isEmpty()) {
            throw new BizException(ResultCode.USER_LOGIN_ERROR);
        }
        // 3、获取用户信息及角色列表
        UserInfo userInfo = op.get();
        List<Role> roles = systemService.getUserRoles(userInfo.getId());
        JSONObject rs = new JSONObject();
        rs.put("token", userInfo.getId());
        rs.put("roles", roles);
        return rs;
    }
}
